﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Threading;
using PubSubLite.Configuration;
using PubSubLite.Utils;

namespace PubSubLite.Messaging.MessageChannels
{
    public class MSMQMessageChannel : IMessageChannel, IDisposable
    {
        public MSMQMessageChannel(IBusConfiguration config)
        {
            Require.Argument.IsNotNull(config, "config");
            _id = Guid.NewGuid();
            _configuration = config;
            _queue = new MessageQueue(@"larmtorget1\private$\test1", QueueAccessMode.SendAndReceive);
            _isRunning = true;
        }

        private Guid _id;
        private MessageQueue _queue;
        private bool _isRunning;
        private Thread _receiveThread;
        private IBusConfiguration _configuration;

        public Guid ID
        {
            get { return _id; }
        }

        public void Send(IMessageBase message)
        {
            _queue.Send(message);
        }

        private event EventHandler<MessageReceivedEventArgs> _messageReceived;

        event EventHandler<MessageReceivedEventArgs> IMessageChannel.MessageReceived
        {
            add { _messageReceived += value; }
            remove { _messageReceived -= value; }
        }

        private void OnMessageReceived(IMessageBase message)
        {
            if (_messageReceived != null)
            {
                _messageReceived(this, new MessageReceivedEventArgs(message));
            }
        }

        private void Receive()
        {
            while (_isRunning)
            {
                var message = _queue.Receive();
                OnMessageReceived((IMessageBase)message.Body);
            }
        }

        public void Dispose()
        {
            _isRunning = false;
            Thread.Sleep(100);
            _receiveThread.Abort();
        }
    }
}
